package gold.digger;

import gold.utils.InputUtil;
import gold.utils.UF;
import javafx.util.Pair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1020 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int numEnclaves(int[][] g) {
            int m = g.length, n = g[0].length;
            boolean[][] vis = new boolean[m][n];
            Deque<int[]> d = new ArrayDeque<>();
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
                        if (g[i][j] == 0) continue;
                        vis[i][j] = true;
                        d.addLast(new int[]{i, j});
                    }
                }
            }
            int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            while (!d.isEmpty()) {
                int[] poll = d.pollFirst();
                int x = poll[0], y = poll[1];
                for (int[] di : dirs) {
                    int nx = x + di[0], ny = y + di[1];
                    if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
                    if (g[nx][ny] != 1) continue;
                    if (vis[nx][ny]) continue;
                    vis[nx][ny] = true;
                    d.addLast(new int[]{nx, ny});
                }
            }
            int ans = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (g[i][j] == 1 && !vis[i][j]) ans++;
                }
            }
            return ans;
        }
    }


    /**
     * Created by fanzhenyu02 on 2020/6/27.
     * Union Find 算法实现
     */
    public class UF {
        // 连通分量个数
        private int count;
        // 存储一棵树
        private int[] parent;
        // 记录树的“重量”
        private int[] size;

        public UF(int n) {
            this.count = n;
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        /* 将 p 和 q 连接 */
        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP == rootQ)
                return;

            // 小树接到大树下面，较平衡
            if (size[rootP] > size[rootQ]) {
                parent[rootQ] = rootP;
                size[rootP] += size[rootQ];
            } else {
                parent[rootP] = rootQ;
                size[rootQ] += size[rootP];
            }
            count--;
        }

        /* 判断 p 和 q 是否连通 */
        public boolean connected(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            return rootP == rootQ;
        }

        private int find(int x) {
            while (parent[x] != x) {
                // 进行路径压缩
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }

        /* 返回图中有多少个连通分量 */
        public int count() {
            return count;
        }

        /* 返回图中联通集合 */
        public Map<Integer, List<Integer>> outputAggregateSet(int n) {
            Map<Integer, List<Integer>> aggregateMap = new HashMap<>();

            // 共有n个集合
            for (int i = 0; i < n; i++) {
                int parentId = find(i);
                if (!aggregateMap.containsKey(parentId)) aggregateMap.put(parentId, new ArrayList<>());
                aggregateMap.get(parentId).add(i);
            }

            System.out.println(aggregateMap.toString());
            return aggregateMap;
        }
    }

    class Solution_Time_Exceed {
        int m = 0, n = 0, sumOneCnt = 0;

        public int numEnclaves(int[][] grid) {
            m = grid.length;
            n = grid[0].length;
            UF uf = new UF(m * n + 1);
            List<Integer> borderList = new ArrayList<>();
            List<Pair<Integer, Integer>> oneList = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] == 1) {
                        ++sumOneCnt;
                        oneList.add(new Pair<>(i, j));// 加到1list
                        if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                            borderList.add(idx(i, j));
                        }
                    }
                }
            }

            for (int i = 0; i < oneList.size(); i++) {
                for (int j = i + 1; j < oneList.size(); j++) {
                    // if near to each other, then uf them
                    int x1 = oneList.get(i).getKey(), y1 = oneList.get(i).getValue();
                    int x2 = oneList.get(j).getKey(), y2 = oneList.get(j).getValue();
                    if ((x1 == x2 && Math.abs(y1 - y2) == 1) || (y1 == y2 && Math.abs(x1 - x2) == 1)) {
                        uf.union(idx(x1, y1), idx(x2, y2));
                    }
                }
            }

            int ans = 0;
            for (int i = 0; i < oneList.size(); i++) {
                boolean curCanOut = false;
                for (int j = 0; j < borderList.size(); j++) {
                    int x1 = oneList.get(i).getKey(), y1 = oneList.get(i).getValue();
                    if (uf.connected(idx(x1, y1), borderList.get(j))) {
                        curCanOut = true;
                        break;
                    }
                }

                if (!curCanOut) ++ans;
            }

            return ans;
        }

        public int idx(int i, int j) {
            return n * i + j;
        }

    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.numEnclaves(InputUtil.toDoubleIntegerArray("[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]")));
        System.out.println(solution.numEnclaves(InputUtil.toDoubleIntegerArray("[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]")));
        System.out.println(solution.numEnclaves(InputUtil.toDoubleIntegerArray("[[0,0,0,1,1,1,0,1,0,0],[1,1,0,0,0,1,0,1,1,1],[0,0,0,1,1,1,0,1,0,0],[0,1,1,0,0,0,1,0,1,0],[0,1,1,1,1,1,0,0,1,0],[0,0,1,0,1,1,1,1,0,1],[0,1,1,0,0,0,1,1,1,1],[0,0,1,0,0,1,0,1,0,1],[1,0,1,0,1,1,0,0,0,0],[0,0,0,0,1,1,0,0,0,1]]")));
        System.out.println(solution.numEnclaves(InputUtil.toDoubleIntegerArray("[[0],[1],[1],[0],[0]]")));

    }

    public static void main(String[] args) throws Exception {
        LC1020 an = new LC1020();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
